<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/7/6 0006
 * Time: 09:58
 */

namespace app\api\controller\v1;


use library\Controller;
use library\File as FileLocal;

class File extends Controller
{
    /**
     * 文件上传
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function save()
    {
        // 文件接收
        if (!($file = $this->getUploadFile()) || empty($file)) {
            $this->error('文件上传异常，文件可能过大或未上传！');
        }
        if (!$file->checkExt(strtolower(sysconf('storage_local_exts')))) {
            $this->error('文件上传类型受限，请在后台配置！');
        }
        if ($file->checkExt('php')) {
            $this->error('可执行文件禁止上传到本地服务器！');
        }
        // 唯一名称
        $ext = strtolower(pathinfo($file->getInfo('name'), PATHINFO_EXTENSION));
        $local = FileLocal::instance('local');
        $name = $local->name($file->getPathname(),$ext, '', 'md5_file');
        $result = $local->save($name,file_get_contents($file->getRealPath()));
        if(is_array($result) && isset($result['url'])){
            $this->success('文件上传成功！', ['site_url' => $result['url']]);
        } else {
            $this->error('文件上传失败，请稍候再试！');
        }
    }

    /**
     * 获取文件对象
     * @return array|bool|\think\File|null
     */
    private function getUploadFile()
    {
        try {
            return $this->request->file('file');
        } catch (\Exception $e) {
            $this->error(lang($e->getMessage()));
        }
        return false;
    }
}